package com.xiaobai.design_pattern.proxy;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author wangtw
 * @date 2023/12/2 21:36
 * @description jdk动态代理处理器
 */
public class JdkGamePlayerProxy implements InvocationHandler {

    private Object targetObject;

    public JdkGamePlayerProxy(Object object) {
        this.targetObject = object;
    }

    private void start() {
        System.out.println("开始时间为" + new Date());
    }

    private void end() {
        System.out.println("结束时间为" + new Date());
    }

    /**
     * 获取角色名称
     * @param operateStep
     */
    private void operatePerson(String operateStep) {
        Class<?> aClass = this.targetObject.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (declaredField.getName().equals("name")) {
                declaredField.setAccessible(true);
                try {
                    Object name = declaredField.get(this.targetObject);
                    System.out.println(name + operateStep + "操作");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *
     * @param proxy 代理对象
     * @param method 方法
     * @param args 方法参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("============开始执行" + method.getName() + "方法==============");
        operatePerson("开始");
        start();
        Object invoke = method.invoke(this.targetObject, args);
        operatePerson("结束");
        end();
        System.out.println("============结束执行" + method.getName() + "方法==============");
        return invoke;
    }
}
